package com.laputa.web.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.apache.struts.actions.EventDispatchAction;

import com.laputa.service.method.BuyService;
import com.laputa.service.model.MainFrameData;

public class BuyAction extends EventDispatchAction {
	BuyService buyService;
	
	public void setBuyService(BuyService buyService) {
		this.buyService = buyService;
	}
	
	public ActionForward buy(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		DynaActionForm toidentify = (DynaActionForm) form;
		
		String groundID = (String) toidentify.get("groundID");
		String userID = ((MainFrameData) request.getSession().getAttribute("userData")).getId().toString();

		System.out.println("from buyaction, userID = " + userID + ", groundID = " + groundID);
		
		boolean success = buyService.buy(userID, groundID);
		if (success) {
			request.setAttribute("message", "购买成功！");
			
			MainFrameData data = buyService.getMainFrameData(userID);
			request.getSession().setAttribute("userData", data);
			
			return mapping.findForward("success");
		}
		else {
			request.setAttribute("resultMessage", "您的金钱不足");
			return mapping.findForward("fail");
		}
	}
}
